import Vue from "vue";
import Router from "vue-router";
import language from "./language.json";
import common from "./nav.config.json";
const LOAD_MAP = {
  "zh-CN": (name) => {
    return () => import(`../pages/zh-CN/${name}.vue`);
  }
};

const load = function(lang, path) {
  return LOAD_MAP[lang](path);
};
const LOAD_DOCS_MAP = {
  "zh-CN": (path, route) => {
    return () => import(`../docs/zh-CN${path}.md`);
  }
};

const loadDocs = function(lang, path, route) {
  return LOAD_DOCS_MAP[lang](path, route);
};
const registerRoute = (commponent, path) => {
  let route = [];
  Object.keys(commponent).forEach((lang, index) => {
    let navs = commponent[lang];
    route.push({
      path: `/${lang}/${path}`,
      redirect: `/${lang}/${path}/installation`,
      component: load(lang, path),
      children: []
    });
    navs.forEach((nav) => {
      if (nav.href) return;
      if (nav.groups) {
        nav.groups.forEach((group) => {
          group.list.forEach((nav) => {
            addRoute(nav, lang, index, path);
          });
        });
      } else if (nav.children) {
        nav.children.forEach((nav) => {
          addRoute(nav, lang, index, path);
        });
      } else {
        addRoute(nav, lang, index, path);
      }
    });
  });
  function addRoute(page, lang, index, path) {
    const component =
      page.path === "/changelog"
        ? load(lang, "changelog")
        : loadDocs(lang, page.path, path);
    let child = {
      path: page.path.slice(1),
      meta: {
        title: page.title || page.name,
        description: page.description,
        lang
      },
      name: `${path}-` + lang + (page.title || page.name),
      component: component.default || component
    };
    route[index].children.push(child);
  }
  return route;
};

let commonRoute = registerRoute(common, "component");

// 基础页面路由
const generateMiscRoutes = (lang: string) => {
  let indexRoute = {
    path: `/${lang}`, // 首页
    meta: { lang },
    name: "home" + lang,
    component: load(lang, "index")
  };
  return indexRoute;
};
let baseRoute = language.map((lang) => {
  return generateMiscRoutes(lang.lang);
});

//判断当前页面是什么语言版本
let userLanguage = window.navigator.language || "zh-CN";
let defaultPath = "/zh-CN";
if (userLanguage.indexOf("zh-") !== -1) {
  defaultPath = "/zh-CN";
}

export default new Router({
  mode: "hash",
  routes: [
    {
      path: "/",
      redirect: defaultPath
    },
    ...commonRoute,
    ...baseRoute
  ]
});
Vue.use(Router);
